/**
 * 报销业务处理实现类
 * @author 郑翎
 * 2015-10-1 11:07:43
 */
package com.cbts.service.travel.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.struts2.ServletActionContext;
import com.cbts.dao.ApplayReimDao;
import com.cbts.dao.BusinessTravelDao;
import com.cbts.dao.BusinessTravelListDao;
import com.cbts.dao.ReceiptDao;
import com.cbts.entity.ApplayReim;
import com.cbts.entity.BusinessTravel;
import com.cbts.entity.BusinessTravelList;
import com.cbts.entity.Receipt;
import com.cbts.entity.ReceiptId;
import com.cbts.service.travel.ApplayReimService;

public class ApplayReimServiceImpl implements ApplayReimService {

	private BusinessTravelListDao businessTravelListdaoImpl;  	//出差记录列表数据处理类
	private BusinessTravelDao businessTraveldaoImpl;			//出差信息数据处理类
	private ApplayReimDao applayReimDaoImpl;					//报销记录数据处理类
	private ReceiptDao receiptDaoImpl;							//收据数据处理类

	private String downloadRootPath = "/files/";				//文件根目录
	private String userFilePath = "";							//用户文件路径
	
	/*
	 * (non-Javadoc)
	 * @see com.cbts.service.travel.ApplayReimService#getNoApplayTravelList(java.lang.String)
	 */
	public List<BusinessTravelList> getNoApplayTravelList(String userid) throws Exception{
		  
		try {
			
			
			String wherehql = "and userInfoByUserid.userid=? and (verifierStatus='待报销'" +
					" or verifierStatus='报销不通过' or " +
					"verifierStatus='审核通过')";
			String[] objet = new String[1];
			objet[0] = userid;
			List<BusinessTravelList> businessTravelLists = businessTravelListdaoImpl
					.findByProperty(wherehql, objet, -1, -1).getPageItems();
			
			return businessTravelLists;
		} catch (Exception e) {
			throw e;
		}
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.cbts.service.travel.ApplayReimService#getTravelInfoList(java.lang.String)
	 */
	public List<BusinessTravel> getTravelInfoList(String travelOrder) throws Exception{
		
		try {
			
			String wherehql = "and businessTravelList.travelOrder=?";
			String[] objet = new String[1];
			objet[0] = travelOrder;
			List<BusinessTravel> businessTravels = businessTraveldaoImpl
					.findByProperty(wherehql, objet, -1, -1).getPageItems();
			
			return businessTravels;
		} catch (Exception e) {
			throw e;
		}

	}
	/*
	 * (non-Javadoc)
	 * @see com.cbts.service.travel.ApplayReimService#getTravelListByOrder(java.lang.String)
	 */
	public BusinessTravelList getTravelListByOrder(String travelOrder) throws Exception{
		try {
			return businessTravelListdaoImpl.get(travelOrder);
		} catch (Exception e) {
			throw e;
		}
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.cbts.service.travel.ApplayReimService#getApplayReim(java.lang.String)
	 */
	public ApplayReim getApplayReim(String travelOrder) throws Exception{
		
		try {
			
			String wherehql = "and travelOrder=?";
			String[] objet = new String[1];
			objet[0] = travelOrder;
			List<ApplayReim> applayReims = applayReimDaoImpl.findByProperty(
					wherehql, objet, -1, -1).getPageItems();
			if(!applayReims.isEmpty()){
				return applayReims.get(0);
			}
			return null;
			
		} catch (Exception e) {
			throw e;
		}
	}

	/*
	 * (non-Javadoc)
	 * @see com.cbts.service.travel.ApplayReimService#getReceiptFile(java.lang.String)
	 */
	public List<Receipt> getReceiptFile(String travelOrder) throws Exception{

		try {
			
			String[] values = new String[1];
			values[0] = travelOrder;
			List<Receipt> receipts =( receiptDaoImpl.findByProperty("and id.applayFileId=?",
					values, -1, -1)).getPageItems();
			
			return receipts;
		} catch (Exception e) {
			throw e;
		}
		
	}
	/*
	 * (non-Javadoc)
	 * @see com.cbts.service.travel.ApplayReimService#saveApplayReim(java.util.List, java.util.List, com.cbts.entity.Receipt, com.cbts.entity.ApplayReim, java.lang.String)
	 */
	@SuppressWarnings("rawtypes")
	public boolean saveApplayReim(List file,
			List<String> fileFileName,Receipt receipt, ApplayReim applayReim,String userid) throws IOException {

		try {
			
			userFilePath = downloadRootPath + userid + "/";
			return upload(file, userFilePath,fileFileName, receipt,  applayReim);
			
		} catch (IOException e) {
			throw e;
		}
		
	}

	/*
	 * @file:文件域列表
	 * @fileName:上传文件的文件名
	 * @path:文件上传的目录，相对目录。 说明：文件上传所存放目录的规则：网站根目录下 files/会员ID/网站类型名称/上传文件分类名称/
	 * @返回结果：一个存放上传文件所在位置相对路径的ArrayList
	 */
	
	public boolean upload(List file, String path, List<String> fileFileName,Receipt receipt,
			ApplayReim applayReim) throws IOException {


		String root = ServletActionContext.getServletContext()
				.getRealPath(path);
		File dir = new File(root);
		
		if (dir.exists() == false) {
			dir.mkdirs();
		}
		
		ArrayList list = new ArrayList();
		ArrayList<Receipt> receiptList = new ArrayList<Receipt>();
		
		for (int i = 0; i < file.size(); ++i) {

			ReceiptId receiptId = new ReceiptId();
			
			receipt.setBfilename(fileFileName.get(i));// 得到上传文件的原名称
			String[] string = fileFileName.get(i).split("\\.");
			String s = UUID.randomUUID().toString();
			
			String name = s+"."+string[string.length-1]; //重命名文件名称
			receiptId.setAfilename(name);
			receiptId.setApplayFileId(receipt.getId().getApplayFileId());			
			Receipt receiptTemp = new Receipt(receiptId, receipt.getBfilename(), receipt.getRemark(), receipt.getFileType());
			
			InputStream is = new FileInputStream(file.get(i).toString());
			File destFile = new File(root, name);
			OutputStream os = new FileOutputStream(destFile);
			byte[] buffer = new byte[1024];

			int length = 0;

			while ((length = is.read(buffer)) > 0) {
				
				os.write(buffer, 0, length);
			}
			list.add(path + name);
			is.close();
			os.close();
			receiptList.add(receiptTemp);
		}

		// 保存报销记录
		if (saveApplayReimByValues(applayReim)) {
			// 将收据信息保存到数据库
			return saveReceipt(receiptList);
		}
		
		return false;
	}

	// 保存报销记录
	public boolean saveApplayReimByValues(ApplayReim applayReim) {
		//不能new一个用户对象然后根据用户Id获取用户信息再赋给这个对象，
		//因为会产生a different object with the same identifier value was already associated with the session错误了！！！
		boolean b = false;
		try {
				if (applayReimDaoImpl.get(applayReim.getTravelOrder())!=null) {ApplayReim tempApplayReim = applayReimDaoImpl.get(applayReim.getTravelOrder());
						
				tempApplayReim.getBusinessTravelList().setVerifierStatus("待报销");
						tempApplayReim.setAmount(applayReim.getAmount());
						tempApplayReim.setAppAmount(applayReim.getAppAmount());
						tempApplayReim.setSaveCost(applayReim.getSaveCost());
						b = applayReimDaoImpl.update(tempApplayReim);
						
					}else {
						
						BusinessTravelList businessTravelList = businessTravelListdaoImpl.get( applayReim.getTravelOrder());
						businessTravelList.setVerifierStatus("待报销");
						b = applayReimDaoImpl.save(applayReim);
						b = businessTravelListdaoImpl.update(businessTravelList);
						
					}
						 return b;
		
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} 
	}

	// 保存收据
	public boolean saveReceipt(List<Receipt> receipts) {
		try {
			return receiptDaoImpl.saveList(receipts);
		} catch (Exception e) {
			return false;
		}
	}
	//删除收据
		public boolean deleteReceipt(ReceiptId receiptId){
			try {
				return receiptDaoImpl.delete(receiptDaoImpl.get(receiptId));
			} catch (Exception e) {
				return false;
			}
		}
	

	public BusinessTravelListDao getBusinessTravelListdaoImpl() {
		return businessTravelListdaoImpl;
	}

	public void setBusinessTravelListdaoImpl(
			BusinessTravelListDao businessTravelListdaoImpl) {
		this.businessTravelListdaoImpl = businessTravelListdaoImpl;
	}

	public BusinessTravelDao getBusinessTraveldaoImpl() {
		return businessTraveldaoImpl;
	}

	public void setBusinessTraveldaoImpl(BusinessTravelDao businessTraveldaoImpl) {
		this.businessTraveldaoImpl = businessTraveldaoImpl;
	}

	public ApplayReimDao getApplayReimDaoImpl() {
		return applayReimDaoImpl;
	}

	public void setApplayReimDaoImpl(ApplayReimDao applayReimDaoImpl) {
		this.applayReimDaoImpl = applayReimDaoImpl;
	}

	public ReceiptDao getReceiptDaoImpl() {
		return receiptDaoImpl;
	}

	public void setReceiptDaoImpl(ReceiptDao receiptDaoImpl) {
		this.receiptDaoImpl = receiptDaoImpl;
	}
	
}
